package com.code.test.second.backtracking;

import java.util.HashSet;
import java.util.Set;

public class SCode3 {


    /**
     * 最长无重复子串
     * https://leetcode.cn/problems/longest-substring-without-repeating-characters/、
     */
    public static void main(String[] args) {
        String input = "pwwkew";
        System.out.println(lengthOfLongestSubstring(input));

    }

    public static int maxLengthOf(String input) {

        int ans = 0;
        int start = 0;
        int end = 0;
        int n = input.length();
        int maxLen = 0;

        Set<Character> set = new HashSet<>();
        while (start < n && end < n) {
            //如果没出现过重复的，则放进去，
            if (!set.contains(input.charAt(end))) {
                set.add(input.charAt(end));
                end++;
                //end-start是当前字符串的长度
                maxLen = Math.max(maxLen, end - start);
            } else {
                //如果出现过了，即代表有重复字符了，则把左指针向前一步，并且把相同的去掉
                set.remove(input.charAt(start));
                start++;
            }
        }
        return maxLen;
    }

    public static int lengthOfLongestSubstring(String s) {

        Set<Character> set = new HashSet();

        int start = 0;
        int end = 0;
        int len = s.length();
        int maxLen = 0;
        while (start < len && end < len) {
            if (!set.contains(s.charAt(end))) {
                // 如果不存在重复，则累加maxLen
                set.add(s.charAt(end));
                end++;
                maxLen = Math.max(maxLen, end - start);
            } else {
                // 如果重复了,start向右移动，并且删除重复元素
                set.remove(s.charAt(start));
                start++;
            }
        }
        return maxLen;
    }
}
